package cn.csc.module.product.validated;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author: 云隐
 * @Date: 2024/01/13
 **/
public class CheckPriceIntervalValidator implements ConstraintValidator<CheckPriceInterval, Object> {

    private String start;
    private String end;
    private String verify;

    @Override
    public void initialize(CheckPriceInterval constraintAnnotation) {
        this.start = constraintAnnotation.start();
        this.end = constraintAnnotation.end();
        this.verify=constraintAnnotation.verify();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        if (o == null) {
            return true;
        }

        BeanWrapper beanWrapper = new BeanWrapperImpl(o);
        Object start1 = beanWrapper.getPropertyValue(start);
        Object end1 = beanWrapper.getPropertyValue(end);
        Object verify1 = beanWrapper.getPropertyValue(verify);

        if (verify1 == null || "0".equals(verify1.toString())) {
            if (start1 == null || end1 == null) {
                return true;
            }else if(Objects.nonNull(start1)
                    && StringUtils.isNotBlank(start1.toString())
                    && Objects.nonNull(end1)
                    && StringUtils.isNotBlank(end1.toString())){
                BigDecimal b1 = new BigDecimal(start1.toString());
                BigDecimal b2 = new BigDecimal(end1.toString());
                if (b1.compareTo(b2) > -1) {
                    return true;
                }
            }
        } else {
            if (Objects.nonNull(start1)
                    && StringUtils.isNotBlank(start1.toString())
                    && Objects.nonNull(end1)
                    && StringUtils.isNotBlank(end1.toString())) {

                BigDecimal b1 = new BigDecimal(start1.toString());
                BigDecimal b2 = new BigDecimal(end1.toString());
                if (b1.compareTo(b2) > -1) {
                    return true;
                }
            }
        }
        return false;
    }
}
